package com.shuoyue.ycgk.ui.questionbank.base;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.base.BaseMvpFragment;
import com.shuoyue.ycgk.base.ListWithPage;
import com.shuoyue.ycgk.entity.Option;
import com.shuoyue.ycgk.entity.QuestionNote;
import com.shuoyue.ycgk.entity.QuestionSimple;
import com.shuoyue.ycgk.ui.common.CollectContract;
import com.shuoyue.ycgk.ui.common.NoteContract;
import com.shuoyue.ycgk.ui.questionbank.note.EditNoteActivity;
import com.shuoyue.ycgk.ui.questionbank.note.NoteAdapter;
import com.shuoyue.ycgk.ui.questionbank.note.NoteListActivity;
import com.shuoyue.ycgk.utils.MyRichTextHelper;
import com.shuoyue.ycgk.utils.NumberUtil;
import com.shuoyue.ycgk.utils.SizeUtil;
import com.shuoyue.ycgk.utils.SpacesItemDecoration;
import com.shuoyue.ycgk.views.dialog.BigImgDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

public abstract class BaseSimpleFragment<T extends BaseMateriFragment, K extends BaseSimpleFragment>
        extends BaseMvpFragment
        implements NoteContract.View,
        CollectContract.View {
    @BindView(R.id.q_type)
    protected TextView qType;
    @BindView(R.id.q_title)
    protected TextView qTitle;
    @BindView(R.id.options)
    protected RecyclerView options;
    @BindView(R.id.aly)
    protected TextView aly;
    @BindView(R.id.now)
    protected TextView now;
    @BindView(R.id.total)
    protected TextView total;
    @BindView(R.id.collection_img)
    protected ImageView collectionImg;
    @BindView(R.id.controll)
    protected Button controll;
    @BindView(R.id.lay_alys)
    protected LinearLayout layAlys;
    @BindView(R.id.right_ans)
    protected TextView rightAns;
    @BindView(R.id.mine_ans)
    protected TextView mineAns;
    @BindView(R.id.use_time)
    protected TextView useTime;
    @BindView(R.id.more_note)
    protected TextView moreNote;
    @BindView(R.id.images)
    protected RecyclerView images;
    @BindView(R.id.notes)
    protected RecyclerView notes;
    @BindView(R.id.collection_lay)
    protected LinearLayout collectionLay;
    @BindView(R.id.aly_tip)
    TextView alyTip;
    @BindView(R.id.note_tip)
    TextView noteTip;

    protected OptionAdapter optionAdapter;
    protected QuestionSimple questionSimple;
    protected SpacesItemDecoration spacesItemDecoration;
    protected BaseQuestionActivity activity;
    protected CollectContract.Presenter collectPresenter;
    protected NoteContract.Presenter notePresenter;

    protected int totalCount;

    NoteAdapter noteAdapter;
    ImageAdapter imageAdapter;
    /**
     * 富文本图片点击
     */
    BigImgDialog bigImgDialog;


    public boolean isShowDK = true;//是否显示?


    public void init(QuestionSimple questionSimple, int total) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("question", questionSimple);
        bundle.putInt("count", total);
        setArguments(bundle);
    }

    @Override
    protected void initData() {
        init();

        notePresenter = new NoteContract.Presenter();
        notePresenter.attachView(this);

        collectPresenter = new CollectContract.Presenter();
        collectPresenter.attachView(this);
        resetTextSize();
    }

    @Override
    public void initParams(Bundle bundle) {
        questionSimple = (QuestionSimple) bundle.getSerializable("question");
        totalCount = bundle.getInt("count");
        activity = (BaseQuestionActivity) getActivity();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_question_simple;
    }

    @Override
    protected void initView() {
    }

    void init() {
        collectionImg.setImageResource(questionSimple.getIsCollect() == 1 ? R.mipmap.collection_y : R.mipmap.collection_n);
        qTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, questionSimple.getTextsize());
        aly.setTextSize(TypedValue.COMPLEX_UNIT_SP, questionSimple.getTextsize());

        String type = "";
        switch (questionSimple.getQuestionType()) {
            case 1:
                type = "单选题";
                break;
            case 2:
                type = "多选题";
                break;
            case 3:
                type = "判断题";
                break;
        }

        MyRichTextHelper.showRich(mContext, questionSimple.getStem(), qTitle);
//        MyRichTextHelper.showRich(mContext, questionSimple.getStem(), qTitle, onImageClickListener);


        qType.setText(type);
        spacesItemDecoration = new SpacesItemDecoration(SizeUtil.dip2px(mContext, 16));
        optionAdapter = new OptionAdapter(questionSimple, isShowDK);
        optionAdapter.setTextSize(questionSimple.getTextsize());
        options.setLayoutManager(new LinearLayoutManager(mContext) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

        options.addItemDecoration(spacesItemDecoration);
        options.setAdapter(optionAdapter);
        optionAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            Option option = optionAdapter.getItem(position);
            Log.e("clickOption", option.getNo());
            doClick(option);
        });
        if (questionSimple.isShowRight()) {
            showRightAnswers();
            setButtonNextText();
        } else {
            changeButtonTextAndTag("下一题", 3);
            layAlys.setVisibility(View.GONE);
        }
        images.setLayoutManager(new LinearLayoutManager(mContext));
        images.addItemDecoration(new SpacesItemDecoration(SizeUtil.dip2px(mContext, 8)));
        imageAdapter = new ImageAdapter(questionSimple.getImgs());
        images.setAdapter(imageAdapter);

        now.setText(questionSimple.getNum() + "");
        total.setText(totalCount + "");

        notes.setLayoutManager(new LinearLayoutManager(mContext));
        notes.addItemDecoration(new SpacesItemDecoration(SizeUtil.dip2px(mContext, 12), false));
        noteAdapter = new NoteAdapter(null);
        notes.setAdapter(noteAdapter);
        noteAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            QuestionNote note = (QuestionNote) adapter.getItem(position);
            switch (view.getId()) {
                case R.id.lay_praise:
                    notePresenter.praiseNote(note, note.getIsLike() == 1 ? 0 : 1);
                    break;
            }
        });
        registEmptyViewSimpleText(noteAdapter, "暂无笔记");
    }

    /**
     * 处理点击事件
     *
     * @param option
     */
    protected void doClick(Option option) {
        //显示正确答案的状态下,点击没有事件
        if (questionSimple.isShowRight()) {
            return;
        }
        if (option.getNo().equals("?")) {
            //点击不会
            option.setSelect(true);
            showRightAnswers();
            questionSimple.setShowRight(true);
            questionSimple.setIsAnswerRight(0);
            List<String> selectOption = new ArrayList<>();
            selectOption.add(option.getNo());
            questionSimple.setMyChooseAnswer((ArrayList<String>) selectOption);

        } else if (questionSimple.getQuestionType() == 1
                || questionSimple.getQuestionType() == 3) {
            //单选 ,判断
            //一但点击,状态改成显示答题解析
            // 如果点击正确答案,跳转到下一题
            // 如果点击错误答案,显示解析

            option.setSelect(!option.isSelect());
            questionSimple.setShowRight(true);
            List<String> selectOption = new ArrayList<>();
            selectOption.add(option.getNo());
            questionSimple.setMyChooseAnswer((ArrayList<String>) selectOption);

            if (option.isRight()) {
                T fragment = (T) getParentFragment();
                if (fragment != null) {
                    fragment.goNext();
                } else {
                    activity.goNext();
                }
            } else {
                setButtonNextText();
            }
            setQuestionAnswerIsRight();
            showRightAnswers();
        } else if (questionSimple.getQuestionType() == 2) {
            //多选
            //点击后,显示选中状态
            option.setSelect(!option.isSelect());
            boolean isAllUnSelect = true;//是否全部没选
            List<String> selectOption = new ArrayList<>();
            for (Option o : questionSimple.getQuestionSimpleOptionDTOS()) {
                if (o.isSelect()) {
                    isAllUnSelect = false;
                    selectOption.add(o.getNo());
                }
            }
            questionSimple.setMyChooseAnswer((ArrayList<String>) selectOption);
            if (isAllUnSelect) {
                //一个都没选,下一题
                changeButtonTextAndTag("下一题", 3);
            } else {
                //选中了,按钮改成完成选中
                changeButtonTextAndTag("完成选择", 2);
            }
        }
        optionAdapter.notifyDataSetChanged();
    }

    /**
     * 显示正确答案视图
     */
    public void showRightAnswers() {
        if (notePresenter != null) {
            notePresenter.getQuestionNotes(questionSimple.getQuestionId(), 1);
        }
        questionSimple.setShowRight(true);
        optionAdapter.notifyDataSetChanged();
        setButtonNextText();
        layAlys.setVisibility(View.VISIBLE);
        //正确答案
        StringBuilder sbRight = new StringBuilder();
        for (Option o : questionSimple.getQuestionSimpleOptionDTOS()) {
            if (o.isRight()) sbRight.append(o.getNo());
        }
        rightAns.setText(sbRight);
        //我的答案
        if (questionSimple.getMyChooseAnswer() == null) {
            mineAns.setText("未作答");
        } else {
            StringBuilder sbMine = new StringBuilder();
            for (String o : questionSimple.getMyChooseAnswer()) {
                if (questionSimple.getQuestionType() == 3) {
                    if (o.equals("A")) {
                        sbMine.append("A");
                    } else if (o.equals("B")) {
                        sbMine.append("B");
                    }
                } else {
                    sbMine.append(o);
                }
            }

            if (sbMine.toString().equals("?")) {
                mineAns.setText("不会");
            } else if (sbMine.length() == 0) {
                mineAns.setText("未作答");
            } else {
                mineAns.setText(sbMine);
            }
        }
        //解析
        MyRichTextHelper.showRich(mContext, questionSimple.getAnalysis(), aly);
        useTime.setText(questionSimple.getUseTime() % 1000 == 0 ?
                ((questionSimple.getUseTime()) / 1000) + "s"
                : NumberUtil.decimal1((((double) questionSimple.getUseTime()) / 1000), 1) + "s");//((double) questionSimple.getUseTime()) / 1000
    }

    Handler handler = new Handler();
    TimerTask clock = new TimerTask() {
        @Override
        public void run() {
            handler.postDelayed(clock, 100);
            questionSimple.setUseTime(questionSimple.getUseTime() + 100);
        }
    };

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if ((isVisibleToUser && isResumed())) {
            onResume();
        } else if (!isVisibleToUser) {
            onPause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            //TODO give the signal that the fragment is visible
            //当前题目变化
            ((BaseQuestionActivity) Objects.requireNonNull(getActivity())).currentSimple = questionSimple;
            //计时
            if (!questionSimple.isShowRight()) {
                handler.postDelayed(clock, 100);
                resetTextSize();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //TODO give the signal that the fragment is invisible
        handler.removeCallbacks(clock);
    }


    @OnClick({R.id.collection_lay, R.id.controll, R.id.write, R.id.more_note})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.collection_lay:
                if (questionSimple.getIsCollect() == 1) {
                    collectPresenter.deleteCollection(questionSimple.getQuestionId(), 1);
                } else {
                    collectPresenter.saveCollect(questionSimple.getQuestionId(), 1);
                }
                collectionLay.setEnabled(false);
                break;
            case R.id.controll:
                controllClick();
                break;
            case R.id.write:
//                EditNoteActivity.startForResult(mActivity, questionSimple.getQuestionId());
                startActivityForResult(new Intent(mActivity, EditNoteActivity.class).putExtra("id", questionSimple.getQuestionId()), EditNoteActivity.REQUEST_CODE);
                break;
            case R.id.more_note:
//                NoteListActivity.start(mActivity, questionSimple.getQuestionId());
                startActivityForResult(new Intent(mContext, NoteListActivity.class)
                                .putExtra("id", questionSimple.getQuestionId())
                        , EditNoteActivity.REQUEST_CODE);
                break;
        }
    }

    protected void controllClick() {
        int tag = (int) controll.getTag();
        switch (tag) {
            case 1://查看解析
                setButtonNextText();
                showRightAnswers();
                break;
            case 2: //完成选中
                chooseDone();
                break;
            case 3://下一题
                T fragment = (T) getParentFragment();
                if (fragment != null) {
                    fragment.goNext();
                } else {
                    activity.goNext();
                }
                break;
        }
    }

    protected void chooseDone() {
        setButtonNextText();
        showRightAnswers();
        setQuestionAnswerIsRight();
    }

    /**
     * case 2: //完成选中
     * case 3://下一题
     * 4:跳转
     *
     * @param text
     * @param tag
     */
    public void changeButtonTextAndTag(String text, int tag) {
        controll.setText(text);
        controll.setTag(tag);
    }


    //<editor-folder desc="笔记,收藏相关回调">


    @Override
    public void setNotes(ListWithPage<QuestionNote> list) {
        noteAdapter.resetData(list.getRecords());
        moreNote.setVisibility(list.getTotal() > 0 ? View.VISIBLE : View.GONE);
    }

    @Override
    public void addNoteSuc() {

    }

    @Override
    public void addCollectSuc() {
        collectionImg.setImageResource(R.mipmap.collection_y);
        collectionLay.setEnabled(true);
        questionSimple.setIsCollect(1);

    }

    @Override
    public void deleteCollectSuc() {
        collectionImg.setImageResource(R.mipmap.collection_n);
        collectionLay.setEnabled(true);
        questionSimple.setIsCollect(0);
    }

    @Override
    public void praiseResult(QuestionNote actionId, boolean isAdd) {
        actionId.setIsLike(isAdd ? 1 : 0);
        actionId.setLikeCount(actionId.getLikeCount() + (isAdd ? 1 : -1));

        noteAdapter.notifyDataSetChanged();
//        for (QuestionNote note : noteAdapter.getData()) {
//            if (note.getId() == actionId) {
//                note.setIsLike(isAdd ? 1 : 0);
//                noteAdapter.notifyDataSetChanged();
//                break;
//            }
//        }

    }
    //</editor-folder >

    protected void setQuestionAnswerIsRight() {
        if (questionSimple.getMyChooseAnswer() == null) {
            return;
        }
        StringBuilder sbMine = new StringBuilder();
        for (String o : questionSimple.getMyChooseAnswer()) {
            sbMine.append(o);
        }

        if (sbMine.toString().equals("?")) {
            return;
        }
        if (sbMine.toString().equals(questionSimple.getRightKey())) {
            whenAnswerRight();
        } else {
            whenAnswerWrong();
        }
    }


    protected void whenAnswerRight() {
        questionSimple.setIsAnswerRight(1);

    }

    protected void whenAnswerWrong() {
        questionSimple.setIsAnswerRight(0);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == EditNoteActivity.REQUEST_CODE) {
            notePresenter.getQuestionNotes(questionSimple.getQuestionId(), 1);
        }
    }


    public void resetTextSize() {
        if (qTitle != null && questionSimple != null) {
            qTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, questionSimple.getTextsize());
        }
        if (aly != null && questionSimple != null) {
            aly.setTextSize(TypedValue.COMPLEX_UNIT_SP, questionSimple.getTextsize());
            aly.setTextSize(TypedValue.COMPLEX_UNIT_SP, questionSimple.getTextsize());
        }
        if (optionAdapter != null
                && questionSimple != null) {
            optionAdapter.setTextSize(questionSimple.getTextsize());
        }
        qType.setTextSize(TypedValue.COMPLEX_UNIT_SP, questionSimple.getTextsize());
        alyTip.setTextSize(TypedValue.COMPLEX_UNIT_SP, questionSimple.getTextsize() + 2);
        noteTip.setTextSize(TypedValue.COMPLEX_UNIT_SP, questionSimple.getTextsize() + 2);

    }

    protected void setButtonNextText() {
        changeButtonTextAndTag(totalCount == questionSimple.getNum() ? "到底了" : "下一题", 3);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }


}
